from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.shortcuts import render, redirect
from webapp import models
from django import forms

# Create your views here.

def depart_list(request):
    """ 部门列表 """
    # 去数据库中获取所有部门列表（查）
    data_list = models.Department.objects.all()
    return render(request, 'depart_list.html', {'data_list': data_list})

def depart_add(request):
    """添加部门"""
    if request.method == 'GET':
        return render(request, 'depart_add.html')
    title = request.POST.get("title")
    models.Department.objects.create(title=title)
    return redirect("/depart/list/")

def depart_delete(request):
    """ 删除部门 """
    nid = request.GET.get('nid')
    models.Department.objects.filter(id=nid).delete()
    return redirect("/depart/list/")

def depart_edit(request, nid):
    """ 修改部门 """
    if request.method == "GET":
        row_object = models.Department.objects.filter(id=nid).first()
        return render(request, 'depart_edit.html', {"row_object": row_object})
    title = request.POST.get("title")
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect("/depart/list/")

def user_list(request):
    """ 用户列表 """
    data_list = models.UserInfo.objects.all()
    return render(request, 'user_list.html', {"data_list": data_list})

def user_add(request):
    """ 添加用户 """
    if request.method == 'GET':
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)
    name = request.POST.get('name')
    password = request.POST.get('password')
    age = request.POST.get('age')
    account = request.POST.get('account')
    create_time = request.POST.get('create_time')
    gender = request.POST.get('gender')
    depart_id = request.POST.get('depart')
    models.UserInfo.objects.create(name=name,password=password,age=age,
                                   account=account,create_time=create_time,
                                   gender=gender,depart_id=depart_id)
    return redirect("/user/list/")

# 编写ModelFrom类
class UserModelForm(forms.ModelForm):
    password = forms.CharField(min_length=6, label="密码")
    class Meta:
        model = models.UserInfo
        fields = ["name","password","age","account","create_time","gender","depart"]
        # widgets = {
        #     "name": forms.TextInput(attrs={"class": "form-control"})
        # }
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label} # 循环找到所有插件，添加"class": "form-control"
def user_model_form_add(request):
    """ 添加用户（ModelFrom版） """
    if request.method == 'GET':
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {"form": form})
    # 进行数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法。加入到数据库中
        form.save()
        return redirect('/user/list/')
    # 在页面上显示错误信息
    return render(request, 'user_model_form_add.html', {"form": form})

def user_edit(request, nid):
    """ 编辑员工 """
    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = UserModelForm(instance=row_object) # 这个参数就会将数据库中查询到的数据自动显示到输入框中
        return render(request, 'user_edit.html', {"form": form})
    form = UserModelForm(data=request.POST, instance=row_object) # 新增的第二个参数就会对数据库中原有的数据行进行更新，而不是在后面添加
    if form.is_valid():
        # 如果数据合法。加入到数据库中
        form.save()
        return redirect('/user/list/')
    # 在页面上显示错误信息
    return render(request, 'user_edit.html', {"form": form})

def user_delete(request, nid):
    row_object = models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')

def pretty_list(request):
    """ 靓号列表 """
    queryset = models.PrettyNum.objects.all().order_by("-level")
    return render(request, 'pretty_list.html', {"queryset": queryset})

class PrettyModelForm(forms.ModelForm):
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile", "level", "status"]
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label} # 循环找到所有插件，添加"class": "form-control"
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")
        return txt_mobile

def pretty_add(request):
    """ 添加靓号 """
    if request.method == 'GET':
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {"form": form})
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_add.html', {"form": form})

def pretty_edit(request, nid):
    """ 编辑靓号 """
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = PrettyModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {"form": form})
    form = PrettyModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_edit.html', {"form": form})

def pretty_delete(request, nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')